/*
 *  Copyright 2013 Utkin Dmitry
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */

#include <QString>
#include <QDebug>
#include "EchoServiceImpl.h"

namespace protoqtrpc
{
namespace samples
{

EchoServiceImpl::EchoServiceImpl():
    mController(NULL),
    mRequest(NULL),
    mResponse(NULL),
    mDone(NULL)
{
}

void EchoServiceImpl::echo(::google::protobuf::RpcController* controller,
                           const EchoRequest* request,
                           EchoResponse* response,
                           ::google::protobuf::Closure* done)
{
    qDebug() << "request received";
    // first response
    response->set_response(request->request());
    qDebug() << "sending first response";
    done->Run();

    if (!isRunning())
    {
        mController = controller;
        mRequest = request;
        mResponse = response;
        mDone = done;
        start();
    }
}

void EchoServiceImpl::run()
{
    Q_ASSERT(mController && mRequest && mResponse && mDone);

    for (int i = 2; i <= 10; ++i)
    {
        sleep(1);
        if (mController->IsCanceled())
        {
            qDebug() << "cancelled";
            break;
        }

        mResponse->set_response(mRequest->request() + ": #"
                               + QString::number(i).toStdString());
        qDebug() << "sending response #" << i;
        mDone->Run();
    }

    mController->Reset();  // cleanup
}

}
}
